package com.google.incomplete.util;

import com.google.incomplete.entity.Unit;
import java.util.HashMap;
import java.util.Map;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.utils.AddrUtil;

public class MemCacheTest {

    public static void main(String[] args) throws Exception {
        MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:11211"));
        MemcachedClient memcachedClient = builder.build();
        System.out.println();
        System.out.println();
        try {
            memcachedClient.set("hello", 0, "Hello,xmemcached");
            String value = memcachedClient.get("hello");
            System.out.println("hello=" + value);

            Unit unit = new Unit();
            unit.setUnitName("神仙道服务器");
            unit.setAddress("区服");
            memcachedClient.set("server1",0,unit);

            //Map map =memcachedClient.getStats();
            Map map = memcachedClient.getStatsByItem("items");
            for (Object key : map.keySet()) {
                HashMap stat = (HashMap)map.get(key);
                if (stat instanceof HashMap) {
                    for (Object key2 : stat.keySet() ) {
                        System.out.println("key:"+key2+"; value:"+stat.get(key2));
                    }
                }
            }

            memcachedClient.delete("hello");
            value = memcachedClient.get("hello");
            System.out.println("hello=" + value);

        } catch (MemcachedException e) {
            System.err.println("MemcachedClient operation fail");
            e.printStackTrace();
        } catch (TimeoutException e) {
            System.err.println("MemcachedClient operation timeout");
            e.printStackTrace();
        } catch (InterruptedException e) {
            // ignore
        }
        System.out.println();
        System.out.println();
        try {
            //close memcached client
            memcachedClient.shutdown();
        } catch (IOException e) {
            System.err.println("Shutdown MemcachedClient fail");
            e.printStackTrace();
        }
    }

}
